package org.example.strategypatterndemo.module1;

import org.example.strategypatterndemo.module1.service.PromotionStrategy;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * PromotionFactory 策略工厂
 * @author dingchen
 * @version 2025/05/29 12:36
**/

@Component
public class PromotionFactory implements InitializingBean {

    private final Map<PromotionType, PromotionStrategy> strategyMap = new HashMap<>();


    private final ApplicationContext applicationContext;

    @Autowired
    public PromotionFactory(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 初始化：从Spring容器中获取所有策略Bean，并按枚举类型注册
     * Key：Bean 的名称（默认是类名首字母小写，如fullReduceStrategy）。
     * Value：Bean 的实例（实现了PromotionStrategy接口的具体策略类）。
     */
    @Override
    public void afterPropertiesSet() {
        // 获取所有实现PromotionStrategy接口的Bean
        Map<String, PromotionStrategy> beans = applicationContext.getBeansOfType(PromotionStrategy.class);
        beans.forEach((beanName, strategy) -> {
            // 从策略Bean中获取对应的枚举类型（需在策略类中增加获取类型的方法）
            // 这里假设策略类通过枚举类型命名（如FullReduceStrategy对应FULL_REDUCE枚举）
            PromotionType type = parseTypeFromBeanName(beanName);
            if (type != null) {
                strategyMap.put(type, strategy);
            }
        });
    }

    /**
     * 从Bean名称解析枚举类型（简化实现，实际可通过注解或接口方法指定类型）
     */
    private PromotionType parseTypeFromBeanName(String beanName) {
        try {
            // Bean名称默认驼峰式，转为枚举大写
            return PromotionType.valueOf(beanName.toUpperCase());
        } catch (IllegalArgumentException e) {
            return null;
        }
    }

    /**
     * 获取策略实例
     */
    public PromotionStrategy getStrategy(PromotionType type) {
        if (!strategyMap.containsKey(type)) {
            throw new IllegalArgumentException("未知促销类型：" + type);
        }
        return strategyMap.get(type);
    }
}
